package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.FtpClient;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.dao.*;
import com.jiangyao.model.dto.CoursewareDTO;
import com.jiangyao.model.dto.*;
import com.jiangyao.model.dto.backend.*;
import com.jiangyao.model.entity.*;
import com.jiangyao.model.vo.*;
import com.jiangyao.model.vo.backend.ChapterItemVO;
import com.jiangyao.model.vo.backend.SubjectChapterVO;
import com.jiangyao.model.vo.backend.SubjectDetailVO;
import com.jiangyao.model.vo.backend.SubjectListVO;
import com.jiangyao.service.IntegralLogService;
import com.jiangyao.service.PublicSubjectService;
import com.jiangyao.service.SubjectService;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author lijing
 * @since 2020-08-12
 */

@Service
public class PublicSubjectServiceImpl extends BaseServiceImpl<ISubjectDao, Subject> implements PublicSubjectService {




    @Autowired
    private DozerBeanMapper dozerBeanMapper;




    @Autowired
    private IPublicProgressDetailDao iPublicProgressDetailDao;

    @Autowired
    private ICollectDao iCollectDao;

    @Autowired
    private ISubjectDataDao iSubjectDataDao;

    @Autowired
    private IChapterDao iChapterDao;

    @Autowired
    private IChapterCoursewareDao iChapterCoursewareDao;

    @Autowired
    private IEvaluationDao iEvaluationDao;
    @Autowired
    private IUserDao iUserDao;

    @Autowired
    private IPublicProgressDao iPublicProgressDao;

    @Autowired
    private ICoursewareDao iCoursewareDao;
    @Autowired
    private IIntegralLogDao iIntegralLogDao;

    @Autowired
    private ISubjectApplyDao iSubjectApplyDao;


    @Autowired
    private IntegralLogService integralLogService;

    @Override
    public PublicSubjectVo getSubjectInfo(PublicSubjectDto publicSubjectDto){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subject_id", publicSubjectDto.getSubjectId());
        queryWrapper.eq("is_public","1");
        queryWrapper.last(" LIMIT 1");
        Subject subject = this.getOne(queryWrapper);
        if (subject == null) {
            throw new ServerException(100, "没有该课程");
        }
        publicSubjectDto.setUserId(getLoginApiUserId());
        //publicSubjectDto.setUserId(1);//后面记得改下
        PublicSubjectVo subjectVo = dozerBeanMapper.map(subject, PublicSubjectVo.class);
        ChapterCourseware chapterCourseware = iPublicProgressDetailDao.getCoursewareName(publicSubjectDto);
        //2021/1/28新增逻辑
        QueryWrapper<SubjectApply> applyQueryWrapper=new QueryWrapper<>();
        applyQueryWrapper.eq("subject_id",publicSubjectDto.getSubjectId());
        applyQueryWrapper.eq("user_id",publicSubjectDto.getUserId());
        Integer count1 = iSubjectApplyDao.selectCount(applyQueryWrapper);

        if(count1>0){
            subjectVo.setCoursewareId(chapterCourseware.getCoursewareId());
            subjectVo.setCoursewareAlias(chapterCourseware.getCoursewareAlias());
            subjectVo.setIsApply(1);
        }else{
            subjectVo.setIsApply(0);
        }
        subjectVo.setCover(FtpClient.fullFtpUrl(subjectVo.getCover()));
        QueryWrapper<Collect> collectQueryWrapper=new QueryWrapper<>();
        collectQueryWrapper.eq("type",4);
        collectQueryWrapper.eq("relate_id",publicSubjectDto.getSubjectId());
        Integer count = iCollectDao.selectCount(collectQueryWrapper);
        subjectVo.setLikeNum(count);

        QueryWrapper<SubjectData> subjectDataQueryWrapper=new QueryWrapper<>();
        subjectDataQueryWrapper.eq("subject_id",publicSubjectDto.getSubjectId());
        SubjectData subjectData;
        subjectData = iSubjectDataDao.selectOne(subjectDataQueryWrapper);
        if(subjectData!=null) {
            subjectVo.setViewNum(subjectData.getViewNum());
        }

        return subjectVo;
    }

    @Override
    public SChapterVo getPublicChapterCourseware(PublicSubjectDto publicSubjectDto){

        publicSubjectDto.setUserId(getLoginApiUserId());
        //publicSubjectDto.setUserId(1);
        SChapterVo sChapterVo=new SChapterVo();
        //sChapterVo.setClsubId(publicSubjectDto.getClsubId());
        List<ChapterVo> chapterAndCourseware = iChapterDao.getPublicChapterCourseware(publicSubjectDto);
        sChapterVo.setChapterVoList(chapterAndCourseware);
        return sChapterVo;
    }


    @Override
    public PublicChapterQuestionVo getQuestionsList(PublicSubjectDto subjectDto){

        //subjectDto.setUserId(1);
        subjectDto.setUserId(getLoginApiUserId());

        PublicChapterQuestionVo chapterQuestionVo=new PublicChapterQuestionVo();

        chapterQuestionVo.setSubjectId(subjectDto.getSubjectId());
        /**
         * 获取课件
         */
        List<QuestionVo> coursewareQuestion = iChapterCoursewareDao.getCoursewareQuestionBySubjectId(subjectDto);
        if(coursewareQuestion!=null){
            chapterQuestionVo.setCoursewareQuestionList(coursewareQuestion);
        }

        for (QuestionVo questionVo:coursewareQuestion
        ) {
            QuestionVo coursewareScore = iChapterCoursewareDao.getPublicCoursewareScore(subjectDto.getUserId(), subjectDto.getSubjectId(), questionVo.getCoursewareId());
            if(coursewareScore!=null){
                questionVo.setStudyStatus(coursewareScore.getStudyStatus());
            }
        }
        /**
         * 获取章节
         */
        List<QuestionVo> chapterQuestion = iChapterDao.getPublicChapterQuestion(subjectDto);
        if(chapterQuestion!=null){
            chapterQuestionVo.setChapterQuestionList(chapterQuestion);
        }

        for (QuestionVo questionVo:chapterQuestion
        ) {
            QuestionVo chapterScore = iChapterDao.getPublicChapterScore(subjectDto.getUserId(), subjectDto.getSubjectId(), questionVo.getChapterId());
            if(chapterScore!=null){
                questionVo.setStudyStatus(chapterScore.getStudyStatus());
            }

        }
        return chapterQuestionVo;
    }


    @Override
    public Page<EvaluationVo> getCommentList(SubjectListPageDto subjectListPageDto){
        Page<EvaluationVo> page=new Page<>(subjectListPageDto.getPageNo(),subjectListPageDto.getPageSize());
        iEvaluationDao.getPublicListPage(page,subjectListPageDto);
        if(CollectionUtils.isEmpty(page.getRecords())){
            return page;
        }

        QueryWrapper<Evaluation> evaluationQueryWrapper =new QueryWrapper<>();
        page.getRecords().forEach(vo->{
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",vo.getUserId());
            userQueryWrapper.last("limit 1");
            User user = iUserDao.selectOne(userQueryWrapper);
            if(user!=null){
                vo.setUserName(user.getUserName());
            }

            QueryWrapper<PublicProgress> progressQueryWrapper=new QueryWrapper<>();
            progressQueryWrapper.eq("user_id",vo.getUserId());
            progressQueryWrapper.eq("subject_id",vo.getSubjectId());
            progressQueryWrapper.eq("status",2);
            Integer coursewareNum = iPublicProgressDao.selectCount(progressQueryWrapper);
            vo.setCoursewareNum(coursewareNum);

            List<CommentReplyVo> replayListById = iEvaluationDao.getReplayListById(vo.getId());
            if(!replayListById.isEmpty()){
                for(CommentReplyVo replay:replayListById){
                    QueryWrapper<User> userWrapper=new QueryWrapper<>();
                    userWrapper.eq("user_id",replay.getUserId());
                    userWrapper.last("limit 1");
                    User users = iUserDao.selectOne(userWrapper);
                    if(users!=null){
                        replay.setUserName(users.getUserName());
                    }
                }
                vo.setCommentReplyVoList(replayListById);
            }

        });
        return page;
    }

    @Override
    public ChapterCoursewareVo getPublicCoursewareInfo(PublicCoursewareDTO coursewareDTO){
        coursewareDTO.setUserId(getLoginApiUserId());//后面加上
        //coursewareDTO.setUserId(1);
        ChapterCoursewareVo coursewareInfo=iChapterCoursewareDao.getPublicCoursewareInfo(coursewareDTO);

        if(coursewareInfo==null){
            throw new ServerException(100,"没有该课程详情");
        }
        //查看是否收藏
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", coursewareDTO.getUserId());
        queryWrapper.eq("relate_id",coursewareDTO.getChcoId());
        queryWrapper.eq("type",2);
        Integer isCollect = iCollectDao.selectCount(queryWrapper);

        coursewareInfo.setIsCollect(isCollect>0?1:0);


        //查看当前课程的课件数
        Integer integer=iChapterCoursewareDao.getPublicCoursewareCount(coursewareDTO);
        coursewareInfo.setOursewarecNum(integer);
        //获取课程资源路径
        QueryWrapper<Courseware> coursewareQueryWrapper = new QueryWrapper<>();
        coursewareQueryWrapper.eq("courseware_id", coursewareInfo.getCoursewareId());
        coursewareQueryWrapper.last(" LIMIT 1");
        Courseware courseware = iCoursewareDao.selectOne(coursewareQueryWrapper);
        if(courseware!=null){
            coursewareInfo.setResourcesPath(FtpClient.fullFtpUrl(courseware.getResourcesPath()));
        }

        return coursewareInfo;
    }
    @Override
    public SChapterCoursewareVo getPublicCoursewareList(PublicCoursewareDTO coursewareDTO){
        List<SimpleChapterCoursewareVo> coursewareList = iChapterCoursewareDao.getPublicCoursewareList(coursewareDTO);
        if(coursewareList.isEmpty()){
            throw new ServerException(100,"没有课程课件列表");
        }

        for (SimpleChapterCoursewareVo coursewareVo:coursewareList){
            QueryWrapper<PublicProgressDetail> progressDetailQueryWrapper=new QueryWrapper<>();
            progressDetailQueryWrapper.eq("chco_id",coursewareVo.getChcoId());
            Integer num = iPublicProgressDetailDao.selectCount(progressDetailQueryWrapper);

            coursewareVo.setWatchNum(num);

        }

        SChapterCoursewareVo sChapterCoursewareVo = new SChapterCoursewareVo();
        sChapterCoursewareVo.setSubjectId(coursewareDTO.getSubjectId());
        sChapterCoursewareVo.setSimpleChapterCoursewareVoList(coursewareList);
        return sChapterCoursewareVo;
    }


    @Override
    public Boolean saveCourseware(PublicStudyCoursewareDto studyCoursewareDto){

        PublicProgressDetail progressDetail = dozerBeanMapper.map(studyCoursewareDto, PublicProgressDetail.class);


        QueryWrapper<ChapterCourseware> chapterCoursewareQueryWrapper=new QueryWrapper<>();
        chapterCoursewareQueryWrapper.eq("chco_id",studyCoursewareDto.getChcoId());
        chapterCoursewareQueryWrapper.last(" LIMIT 1");
        ChapterCourseware chapterCourseware = iChapterCoursewareDao.selectOne(chapterCoursewareQueryWrapper);

        progressDetail.setChapterId(chapterCourseware.getChapterId());
        progressDetail.setCoursewareId(chapterCourseware.getCoursewareId());
        progressDetail.setUserId(getLoginApiUserId());
        //progressDetail.setUserId(1);

        //写入progress_detail表数据
        iPublicProgressDetailDao.insert(progressDetail);

        //写入观看次数
        SubjectData subjectData;
        QueryWrapper<SubjectData> subjectDataQueryWrapper=new QueryWrapper<>();
        subjectDataQueryWrapper.eq("subject_id",chapterCourseware.getSubjectId());
        subjectDataQueryWrapper.last("limit 1");
        subjectData = iSubjectDataDao.selectOne(subjectDataQueryWrapper);
        if(subjectData==null){
            SubjectData subjectData1=new SubjectData();
            subjectData1.setSubjectId(chapterCourseware.getSubjectId());
            subjectData1.setViewNum(1);
            iSubjectDataDao.insert(subjectData1);
        }else {
            UpdateWrapper<SubjectData> subjectDataUpdateWrapper = new UpdateWrapper<>();
            subjectDataUpdateWrapper.eq("subject_id", chapterCourseware.getSubjectId());
            subjectDataUpdateWrapper.set("view_num", subjectData.getViewNum() + 1);
            iSubjectDataDao.update(null, subjectDataUpdateWrapper);
        }
        //准备学习时长

        long diff = (studyCoursewareDto.getEndTime().getTime() - studyCoursewareDto.getStartTime().getTime()) / 1000;
        long diffTime=studyCoursewareDto.getStudyTime()>0?studyCoursewareDto.getStudyTime():diff;

        //准备学习进度百分比
        QueryWrapper<Courseware> coursewareQueryWrapper=new QueryWrapper<>();
        coursewareQueryWrapper.eq("courseware_id",chapterCourseware.getCoursewareId());
        coursewareQueryWrapper.last("limit 1");
        Courseware courseware = iCoursewareDao.selectOne(coursewareQueryWrapper);
        double progressPercent = (Math.round(courseware.getTotalTime() / diffTime) / 100.0);

        QueryWrapper<PublicProgress> progressQueryWrapper =new QueryWrapper<>();
        progressQueryWrapper.eq("user_id",getLoginApiUserId());
        //progressQueryWrapper.eq("user_id",1);
        progressQueryWrapper.eq("chco_id",studyCoursewareDto.getChcoId());
        progressQueryWrapper.eq("subject_id",studyCoursewareDto.getSubjectId());
        progressQueryWrapper.last("limit 1");
        PublicProgress progress1 = iPublicProgressDao.selectOne(progressQueryWrapper);
        Integer progressCount = iPublicProgressDao.selectCount(progressQueryWrapper);
        Integer status=diffTime>0&&diffTime<courseware.getTotalTime()?1:(diffTime>=courseware.getTotalTime()?2:0);

        if(progressCount==0){
            PublicProgress progress=dozerBeanMapper.map(progressDetail,PublicProgress.class);
            progress.setProgress(diffTime);
            progress.setProgressPercent(progressPercent);
            progress.setStatus(status);
            iPublicProgressDao.insert(progress);
        }else if(progressCount>0&&progress1.getStatus()!=2){
            UpdateWrapper<PublicProgress> updateWrapper=new UpdateWrapper<>();
           updateWrapper.eq("user_id",getLoginApiUserId());
            //updateWrapper.eq("user_id",1);
            updateWrapper.eq("chco_id",studyCoursewareDto.getChcoId());
            updateWrapper.eq("subject_id",studyCoursewareDto.getSubjectId());

            updateWrapper.set("progress",diffTime);
            updateWrapper.set("progress_percent",progressPercent);
            updateWrapper.set("status",status);
            iPublicProgressDao.update(null,updateWrapper);
        }

        if(status==2){
            QueryWrapper<PublicProgress> progress2=new QueryWrapper<>();
            progress2.eq("user_id",getLoginApiUserId());
            //progress2.eq("user_id",1);
            progress2.eq("chco_id",studyCoursewareDto.getChcoId());
            progress2.eq("subject_id",studyCoursewareDto.getSubjectId());
            progress2.last(" limit 1");
            PublicProgress progress = iPublicProgressDao.selectOne(progress2);

            QueryWrapper<IntegralLog> integralLogQueryWrapper=new QueryWrapper<>();
            integralLogQueryWrapper.eq("user_id",getLoginApiUserId());
            //integralLogQueryWrapper.eq("user_id",1);
            integralLogQueryWrapper.eq("source_id",progress.getId());
            integralLogQueryWrapper.eq("source_type",10);
            integralLogQueryWrapper.eq("status",1);
            Integer count = iIntegralLogDao.selectCount(integralLogQueryWrapper);
            if(count==0){
                IntegralLog integralLog=dozerBeanMapper.map(progress,IntegralLog.class);
                integralLog.setUserId(getLoginApiUserId());
                //integralLog.setUserId(1);
                integralLog.setSourceType(10);
                integralLog.setSourceId(progress.getId().toString());
                integralLog.setIntegralNum(5);
                integralLog.setCreateTime(new Date());
                integralLog.setStatus(1);
                integralLogService.saveLogAndUpdateUserIntegral(true,integralLog);
            }

        }
        return true;

    }

    @Override
    public Boolean saveApply(PublicSubjectDto publicSubjectDto){
        SubjectApply subjectApply = dozerBeanMapper.map(publicSubjectDto, SubjectApply.class);
        subjectApply.setUserId(getLoginApiUserId());
        QueryWrapper<SubjectApply> applyQueryWrapper = new QueryWrapper<>();
        applyQueryWrapper.eq("user_id",subjectApply.getUserId());
        applyQueryWrapper.eq("subject_id",subjectApply.getSubjectId());
        applyQueryWrapper.last(" limit 1");
        Integer count = iSubjectApplyDao.selectCount(applyQueryWrapper);
        if(count>0){
            throw new ServerException(100,"用户已报名该课程");
        }else {
            subjectApply.setCreateTime(new Date());
            iSubjectApplyDao.insert(subjectApply);
        }

        return true;
    }

    @Override
    public Boolean saveComment(PublicEvaluationDto evaluationDto){
        Evaluation evaluation = dozerBeanMapper.map(evaluationDto, Evaluation.class);
        evaluation.setUserId(getLoginApiUserId());
        //evaluation.setUserId(1);
        evaluation.setCreateTime(new Date());
        //业务不明确，默认审核通过
        evaluation.setStatus(1);
        iEvaluationDao.insert(evaluation);
        return true;
    }

    @Override
    public Boolean saveReply(PublicEvaluationDto evaluationDto){
        Evaluation evaluation = dozerBeanMapper.map(evaluationDto, Evaluation.class);
        evaluation.setUserId(getLoginApiUserId());
        //evaluation.setUserId(1);
        evaluation.setCreateTime(new Date());
        //业务不明确，默认审核通过
        evaluation.setStatus(1);
        if(evaluationDto.getReleteId()==0){
            throw new ServerException(100,"回复课程失败，无对应的评论");
        }
        evaluation.setReleteId(evaluationDto.getReleteId());
        evaluation.setType(1);
        iEvaluationDao.insert(evaluation);
        return true;
    }



    @Override
    public Boolean getLike(PublicSubjectDto subjectDto){
        QueryWrapper<Collect> collectQueryWrapper=new QueryWrapper<>();
        collectQueryWrapper.eq("relate_id",subjectDto.getSubjectId());
        collectQueryWrapper.eq("user_id",getLoginApiUserId());
        //collectQueryWrapper.eq("user_id",1);
        collectQueryWrapper.eq("type",4);
        collectQueryWrapper.eq("action",2);
        Integer count = iCollectDao.selectCount(collectQueryWrapper);
        return  count>0?true:false;
    }

}
